//获取应用实例
const app = getApp();
const network_utils = require('../../http/NetworkUtils.js');
const constants = require('../../common/Constants.js');
const regexUtils = require('../../utils/RegexUtils.js');
const umfDialog = require('../../utils/UmfDialog');
import LoginUtils from '../../model/LoginUtils';
import * as UserUtils from '../../model/UserUtils';
import DebugUtils from '../../utils/DebugUtils';
import PageRouter from '../../utils/PageRouter';
import * as SensorUtils from '../../utils/SensorUtils';
import * as UmfUtils from '../../utils/UmfUtils';
import UmfLog from '../../utils/UmfLog';

import { $Toptips } from '../../components/CompRouter';

/**页面返回记录*/
const PageResults = {
    MODIFY_PWD: constants.LoginFrom.MODIFY_PWD
};

Page({
    data: {
        loading: false,
    },

    onLoad: function (options) {
        //记住账号
        let lastLoginUser = UmfUtils.getStorageSync(constants.Keys.LAST_LOGIN_USER);
        lastLoginUser && this.setData({
            assistId: lastLoginUser.assistId
        });

        let from = options.from;
        this._processFrom(from, options);
    },



    onHide: function(){
        //调试代码. 关闭摇一摇
        if(DebugUtils.isDebug()) {
            wx.stopAccelerometer();
        }
    },

    onShow: function (options) {
        //调试代码. 打开摇一摇进入调试页面
        if(DebugUtils.isDebug()){
            wx.onAccelerometerChange(function(res) {
                SensorUtils.shake(res,()=>{
                    wx.stopAccelerometer();
                    PageRouter.navigateTo({
                        url: "../debug/test"
                    });
                });
            });
        }

        if (PageResults.MODIFY_PWD === this.data.pageResult) {
            this._onCompleteChangePwd();
        }
    },

    onUnload: function () {
        //用户按返回的场合，检查登录态
        app.checkLoginState({}, {
            onLogin: () => {
                //需要登录的场合，强制登录
                setTimeout(() => {
                    PageRouter.anyNavigateTo("pages/login/login", "?from=" + constants.LoginFrom.FORCE_LOGIN, (curPage) => {
                        $Toptips.error({text: "必须登录才能继续使用"});
                    });
                }, 200);
            }
        });
    },

    /**
     * 登录按钮提交事件
     */
    onSubmit: function (e) {
        this.setData({
            loginToken: '',
            assistId: e.detail.value.accountInput,
            userId: e.detail.value.userNameInput,
            password: e.detail.value.pwdInput
        });

        let errorMsg = this._checkForm();
        if (errorMsg) {
            $Toptips.error({text: errorMsg});
        } else {
            this.setData({
                loading: true,
            });
            this._doLogin();
        }
    },

    /**
     * navigateBack返回接收数据
     * @param data
     * @param from
     */
    pageForResult(data, from){
        if (constants.LoginFrom.MODIFY_PWD === from) {
            this.setData({
                pageResult: PageResults.MODIFY_PWD
            });
        }
    },

    /**
     * 处理跳转场合
     * @param from
     * @param options
     * @private
     */
    _processFrom: function (from, options) {
        if (constants.LoginFrom.AUTO_LOGIN === from) {
            let loginToken = options.loginToken;
            //自动登录的场合
            wx.showToast({
                title: '登录中',
                icon: 'loading',
                duration: 30000,
                mask: true,
            });
            this.setData({
                loginToken: loginToken
            });
            this._doLogin();
        } else if (constants.LoginFrom.KICK_OUT === from) {
            $Toptips.error({text: "您的账号在其他设备登录，请重新登录"});
        } else if (constants.LoginFrom.SESSION_OUT === from) {
            $Toptips.error({text: "登录超时，请重新登录"});
        } else if (constants.LoginFrom.FORCE_LOGIN === from) {
            $Toptips.error({text: "必须登录才能继续使用"});
        } else if (constants.LoginFrom.USER_STATE_CLOSED === from) {
            umfDialog.show("您的账号已被管理员admin停用,如需启用请联系管理员.");
        } else if (constants.LoginFrom.USER_STATE_NO_PERM === from) {
            umfDialog.show("您的权限已被管理员admin修改,请重新登录.");
        }
    },

    _checkForm: function () {
        let values = [
            [this.data.assistId, constants.RegexTypes.ASSIST_ID],
            [this.data.userId, constants.RegexTypes.USER_ID],
            // [this.data.password, constants.RegexTypes.LOGIN_PWD]
        ];

        let errorMsg = regexUtils.regexTypesWithMsg(values);
        if (errorMsg) {
            return errorMsg;
        }
        if (this.data.password.length < 6) {
            return "请输入6-32位密码";
        }
        return "";
    },

    /**
     * 登录
     */
    _doLogin: function () {
        UmfLog.log('[login] start.');
        //调用登录接口
        wx.login({
            success: (e) => {
                //微信登录态
                app.globalData.states.wxLogin = true;
                let code = e.code;
                this._umfLogin(code);
            },

            fail: (e) => {
                this._onLoginFailed();
            }
        });
    },

    /**
     * 请求后台登录接口
     *
     * @param code wx.login登录时获取的 code,用于后续获取session_key
     */
    _umfLogin: function (code) {
        if (this.data.loginToken) {
            //自动登录
            this._requestAutoLogin(code);
        } else {
            //手动登录
            this._requestLogin(code);
        }
    },

    _requestAutoLogin: function (code) {
        let params = {
            code: code,
            token: this.data.loginToken,
        };
        network_utils.buildRequest(constants.Interfaces.FUNC_AUTO_LOGIN, params, {
            doHttpSucess: (response) => {
                if (constants.RetCodes.SUCCESS === response.retCode) {
                    this._onLoginSuccess(response);
                    //自动登录的场合强制修改密码
                    wx.navigateTo({
                      url: './modifyPassword/modifyPassword'
                    });
                    return true;
                }
                return false;
            },
            doComplete: () => {
                wx.hideToast();
            }
        }, false).send();
    },

    _requestLogin: function (code) {
        let params = {
            code: code,
            assistId: this.data.assistId,
            userId: this.data.userId,
            password: this.data.password
        };
        network_utils.buildRequest(constants.Interfaces.FUNC_LOGIN, params, {
            doHttpSucess: (response) => {
                if (constants.RetCodes.SUCCESS === response.retCode) {
                    this._onLoginSuccess(response);
                    //[审核账号 特殊处理]
                    if (constants.isWeAudit
                        && this.data.assistId === constants.weAuditUser.assistId
                        && this.data.userId === constants.weAuditUser.userId) {
                        this._onCompleteChangePwd();
                        return true;
                    }

                    if (this.data.password === constants.INITIIAL_PWD) {
                        wx.navigateTo({
                            url: './modifyPassword/modifyPassword'
                        });
                    } else {
                        this._onCompleteChangePwd();
                    }
                    return true;
                }
                return false;
            },

            doComplete: () => {
                this.setData({
                    loading: false
                });
            }
        }, false).send();
    },

    _onLoginSuccess: function (result) {
        app.globalData.states.isLoginProcess = false;
        //保存登录信息
        LoginUtils.saveLoginData(app, result);
    },

    _onCompleteChangePwd: function () {
        //更新修改原始密码状态
        app.globalData.userData.oriPwdChange = true;
        UserUtils.saveUserInfo(app.globalData.userData);

        this._processNav();
    },

    /**
     * 处理跳转
     * @private
     */
    _processNav() {
        let lastUser = UmfUtils.getStorageSync(constants.Keys.LAST_LOGIN_USER);
        let curUser = app.globalData.userData;

        let isChangeUser = false;
        if (lastUser && (lastUser.agentId !== curUser.agentId || lastUser.userId !== curUser.userId)) {
            isChangeUser = true
        }
        //保存最后一次登录的用户名
        UmfUtils.setStorageSync(constants.Keys.LAST_LOGIN_USER, {
            assistId: curUser.assistId,
            agentId: curUser.agentId,
            userId: curUser.userId,
        });

        let pages = getCurrentPages();
        wx.navigateBack({
            delta: isChangeUser? (pages.length - 1) : 1,
        });
    },

    _onLoginFailed: function () {
        umfDialog.show("登录失败");
        wx.hideToast();
        this.setData({
            loading: false
        });
    }
});


